package com.example.courseapp.bean;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.example.courseapp.R;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 支持显示各层速率信息的TableView，用法很简单，只需要传入一个IeBin对象，
 * 他就能根据对应制式将数据展示到表格中,
 * 更新数据使用updateData()方法
 */
public class LayerInfoTableView extends RelativeLayout {
    private static final String TAG = "LayerInfoTableView";

    /**
     * xml中可配置的属性
     */
    private int head_bg;
    private int borderWidth;
    private int headHeight;
    private int contentHeight;

    private Context mContext;
    private final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;
    private final int FILL_PARENT = ViewGroup.LayoutParams.MATCH_PARENT;

    private List<ColumnData> data;

    public LayerInfoTableView(Context context) {
        super(context);
        this.mContext = context;
        init(context, null);
    }

    public LayerInfoTableView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init(context, attrs);
    }

    public LayerInfoTableView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LayerInfoTableView);
            head_bg = typedArray.getColor(R.styleable.LayerInfoTableView_head_bg, getResources().getColor(android.R.color.white));
            headHeight = (int) typedArray.getDimension(R.styleable.LayerInfoTableView_head_height, 100);
            contentHeight = (int) typedArray.getDimension(R.styleable.LayerInfoTableView_content_height, 100);
            borderWidth = (int) typedArray.getDimension(R.styleable.LayerInfoTableView_border, 1);
            typedArray.recycle();
        }

        // 屏幕分辨率
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int screenW = displayMetrics.widthPixels;
        int screenH = displayMetrics.heightPixels;

        // 初始化表头
        LayoutInflater.from(mContext).inflate(R.layout.layout_layer_info, this);
        TableRow mTableRow = makeTableRows(true, "名称", "UL(kps)", "DL(kps)");
        TableLayout tableHeader = this.findViewById(R.id.table_head);
        tableHeader.setBackgroundColor(head_bg);
        tableHeader.setStretchAllColumns(true);
        tableHeader.addView(mTableRow, new TableLayout.LayoutParams(WRAP_CONTENT, FILL_PARENT));

        Log.d(TAG, "init layerInfoTableView complete,screenW=" + screenW + ",screenH=" + screenH);
    }

    public void setData(IeNr5gBin ieBin) {
        // 解析表格体数据
        data = parseTableContent(ieBin);
        // 设置数据
        initTableContent(data);
    }

    private List<ColumnData> parseTableContent(IeNr5gBin nr5gBin) {
        List<ColumnData> columnDataList = new ArrayList<>();
        if (nr5gBin == null) {
            return columnDataList;
        }

        float sdapDlRate = nr5gBin.getDlSdapThroughput();
        float sdapUlRate = nr5gBin.getUlSdapThroughput();
        columnDataList.add(new ColumnData("SDAP", sdapUlRate, sdapDlRate));

        float pdcpDlRate = nr5gBin.getDlThroughput();
        float pdcpUlRate = nr5gBin.getUlThroughput();
        columnDataList.add(new ColumnData("PDCP", pdcpUlRate, pdcpDlRate));

        float macDlRate = nr5gBin.getMacThroughput();
        float macUlRate = nr5gBin.getMacThroughput();
        columnDataList.add(new ColumnData("MAC", macUlRate, macDlRate));

        float phyDlRate = nr5gBin.getPhyThroughput();
        float phyUlRate = nr5gBin.getPhyThroughput();
        columnDataList.add(new ColumnData("PHY", phyUlRate, phyDlRate));

        float rlcDlRate = nr5gBin.getDlThroughput();
        float rlcUlRate = nr5gBin.getUlThroughput();
        columnDataList.add(new ColumnData("RLC", rlcUlRate, rlcDlRate));
        return columnDataList;
    }

    private void initTableContent(List<ColumnData> dataList) {
        LayoutInflater.from(mContext).inflate(R.layout.layout_layer_info, this);
        TableLayout tabContent = this.findViewById(R.id.table_content);
        tabContent.setStretchAllColumns(true);
        tabContent.removeAllViews();

        for (ColumnData columnData : dataList) {
            String name = columnData.name;
            String ulSpeed = floatToStr(columnData.ulRate);
            String dlSpeed = floatToStr(columnData.dlRate);
            TableRow tableRow = makeTableRows(false, name, ulSpeed, dlSpeed);
            tabContent.addView(tableRow, new TableLayout.LayoutParams(WRAP_CONTENT, FILL_PARENT));
        }
    }

    private TableRow makeTableRows(boolean isHead, String... otherRows) {
        int tCellW = getWidth() / otherRows.length;
        TableRow mTableRow = new TableRow(mContext);
        for (int i = 0; i < otherRows.length; i++) {
            TextView ulView = makeCellView(isHead, tCellW, otherRows[i]);
            mTableRow.addView(ulView, i);
        }
        return mTableRow;
    }

    private TextView makeCellView(boolean isHead, int cellWidth, String name) {
        TextView celView = new TextView(mContext);
        celView.setSingleLine(true);
        celView.setSelected(true);
        celView.setText(name);
        celView.setWidth(cellWidth);
        celView.setTextColor(Color.BLACK);
        celView.setGravity(Gravity.CENTER);
        celView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        celView.setHeight(isHead ? headHeight : contentHeight);
        if (isHead) {
            celView.setBackgroundColor(head_bg);
        }
        return celView;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (data == null || data.size() == 0) {
            return;
        }

        int mCol = 3;
        int mRow = data.size();
        int cellWidth = getWidth() / mCol;
        Paint paint = new Paint();
        paint.setStrokeWidth(borderWidth);
        paint.setColor(Color.rgb(79, 129, 189));
        paint.setStyle(Paint.Style.STROKE);

        // 绘制header的边框
        canvas.drawRect(0, 0, getWidth(), headHeight, paint);
        // 画列分割线
        for (int i = 0; i < mCol + 1; i++) {
            int startX = cellWidth * i;
            canvas.drawLine(startX, 0, startX, getHeight(), paint);
        }
        // 画行分割线
        for (int j = 1; j < mRow + 1; j++) {
            int startY = contentHeight * j + headHeight;
            canvas.drawLine(0, startY, getWidth(), startY, paint);
        }
        super.dispatchDraw(canvas);
    }

    public String floatToStr(float f) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(f);
    }

    static class ColumnData {
        String name;
        float ulRate;
        float dlRate;

        public ColumnData(String name, float ulRate, float dlRate) {
            this.name = name;
            this.ulRate = ulRate;
            this.dlRate = dlRate;
        }
    }

}

